package com.ssu.judea.travlog.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.util.Log;

public class HttpHelper {
	private HttpClient client;
	private HttpResponse response;
	
	
	public String getResultFromUrl(String currentUrl, ArrayList<TravlogNameValuePair> list, boolean isPost) {

		String url = currentUrl;
		Log.v("changdoc","currentUrl= http:"+currentUrl);
		for(int i = 0;i<list.size();i++){
			Log.v("changdoc","currentParams : "+list.get(i).getName()+" : "+list.get(i).getValue());
		}
		String result = "";
		
		try {
			URI uri = new URI("http", url, null);
			
			HttpGet get = null;
			HttpPost post = null;
			
			if(isPost)post = new HttpPost(uri);
			else get = new HttpGet(uri);

			//HttpConnectionParams.setConnectionTimeout(hp,5000);
			
			if(client == null)
				client = new DefaultHttpClient();
			
			
			response = null;
			
			if(isPost){
				post.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
				response = client.execute(post);
			}else{
				response = client.execute(get);
			}

			if (response != null) {
				HttpEntity entity = response.getEntity();
				result = convertStreamToString(entity.getContent());
			} else {
				return "error";
			}

		} catch (Exception e) {
			Log.e("changdoc", e.getMessage());
			result = "error";
		}
		
		if(result.trim().equals("Please request valid"))
			result = "error";
		Log.v("changdoc","result= "+result);
		return result;

	}

	private String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(is), 8 * 1024);
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}
}
